package com.question.common.utils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 登录IP工具类
 *
 * @author star
 * @since 2022/7/8
 */
public class IpUtil {

    public static final String UNKNOWN = "unknown";

    /**
     * 获取访问用户的客户端IP（适用于公网与局域网）.
     */
    public static String getIpAddress(final HttpServletRequest request) {
        if (Objects.nonNull(request)) {
            String ip = request.getHeader("x-forwarded-for");

            if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }

            if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("X-Forwarded-For");
            }

            if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }

            if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("X-Real-IP");
            }

            if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
            // 多个路由时，取第一个非unknown的ip
            final String[] arr = ip.split(",");
            for (final String str : arr) {
                if (StringUtils.isNotBlank(str) && !UNKNOWN.equalsIgnoreCase(str)) {
                    ip = str;
                    break;
                }
            }
            return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
        }
        return null;
    }

}
